package com.ruoyi.manage.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: xushuai
 * @name：AliPayUtils
 * @Date：2024/3/6 19:19
 */
@Component
public class AliPayUtils {
    // 应用私钥
    public static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDTWkyRWuEAoNDuyk/uoETtQNI/1i0FJyeMpVquvUQ6X1kNBBo1e8MGJ2zxabNJvydu47rqEuGi66nfFcBOQ+iHBIj/REkmw3OXKXYlf7/wQxnwd2JbE6MPVadJyRgadhmAqprC45oa/915MCEpwXGl6jElrN4xGXxrI6RzjMn01exyWlz8JbzITy5jQehKIb71VKCIjF+jZJRlmAnjPuPCGKfkNs9Yylh9dcXeDV0X5q44ioQ19bGP8ZUlSkELLYK0ku0zW+tq3ebmx6SllCseCp+6VlkGzbXiL1lkZWFBsVXa7ra7lxY3hloHoHzKhmwq1aveROQuH45hARrTZ/ilAgMBAAECggEALwkkiyC3fEVN2iaqHUgLruVDJTPL9x6cnZ9bDBJQ8dCwZ8Ym8wok/+ScSSml3d6tru79dQRYtMJPnrcfggt43ztyJaUTxo2u1tBCW9wPYi/8wNhAylYXbt04CqK3O4RW7pyJLqAqdqHEryi36KwFV9BDuce79x9d4hYfjhuiAluFs0yKclt1TDD4poNBRTbu8k75gSBV3qD+YML9OSIw44Tyudl7lZzMvrxehaacrvMdMdvFdz5Xefg0wQBm1Q3BYzDU+zNx7+JQ4z9y4ndsFa0CuJ42MK52MyCX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8kZG9G+BMIeYpdDOcHF8NHQ517qaGIUzpjzKMowIF2EpGDLjQXGbUc+A11NwK80WFBG/AIc9IyBZ5wMBflHbd+pVuMyRNuXUkPHWjJx1FLJgUkZ5VFZ93fLPMpfoUj+ISncNVsYFNvSCWVV0nOOIpM8uUjkKTzDFmuwyIY7D1G122UR2SY2r5rnzka9MnjPLml2/7//90kV8rIoLHK6T75YwyHv43ihvtIJKeVSL9HppEqw+3JKuJshmHYuUmtGq238BG8BPlAKYdlkHUqlmGrRwIDAQAB";
    public static final String serverUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    public static final String appId = "9021000138681497";
    public static final String signType = "RSA2";

    @Bean
    public AlipayClient createAlipayClient() throws AlipayApiException {
        // 调用支付宝支付时使用的配置信息
        AlipayConfig alipayConfig = new AlipayConfig();
        // 支付宝网关地址
        alipayConfig.setServerUrl(serverUrl);
        // 支付宝沙箱账号ID
        alipayConfig.setAppId(appId);
        alipayConfig.setPrivateKey(privateKey);
        // 设置参数格式 json
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        // 设置编码方式
        alipayConfig.setCharset("UTF-8");
        // 设置签名加密方式
        alipayConfig.setSignType(signType);
        // todo: 创建支付宝支付客户端对象
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        return alipayClient;
    }

    // 支付完成后的回调验签
    public static boolean callBack(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayPublicKey,
                "UTF-8",
                signType); //调用SDK验证签名
        // 返回验签的结果
        return signVerified;
    }

    public static Map<String,String> scanOrder(AlipayTradeQueryResponse response) throws AlipayApiException, JsonProcessingException {
        Map<String,String> hashMap = new HashMap<>();
        if (response.isSuccess()) {
            // 获取响应结果,并解析结果
            String result = response.getBody();
            // json转java对象(map)
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(result, Map.class);
            Map map1 = (Map)map.get("alipay_trade_query_response");
            String code = (String)map1.get("code");
            String trade_status = (String)map1.get("trade_status");
            hashMap.put("code",code);
            hashMap.put("trade_status",trade_status);
            return hashMap;
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
